﻿namespace ufida.u9.ait.openapi
{
	using System;
	using System.Collections.Generic;
	using System.Text;
    using ufida.u9.ait.openapi.utils;
    using UFIDA.U9.Base;
    using UFIDA.U9.Base.Currency;
    using UFIDA.U9.CBO.Pub.Controller;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.InvDoc.TransferIn;
    using UFIDA.U9.InvDoc.TransferOut;
    using UFIDA.U9.Lot;
    using UFIDA.U9.MO.SFC.DispatchCODocApprove.Data;
    using UFIDA.U9.QC.QCDocBE;
    using UFIDA.U9.SM.DealerSO;
    using UFSoft.UBF.AopFrame;
    using UFSoft.UBF.Business;
    using UFSoft.UBF.Util.Context;

	/// <summary>
	/// TransferInSaveExSV partial 
	/// </summary>	
	public partial class TransferInSaveExSV 
	{	
		internal BaseStrategy Select()
		{
			return new TransferInSaveExSVImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class TransferInSaveExSVImpementStrategy : BaseStrategy
	{
		public TransferInSaveExSVImpementStrategy() { }

		public override object Do(object obj)
		{						
			TransferInSaveExSV bpObj = (TransferInSaveExSV)obj;

            try
            {
                if (bpObj.Data == null || bpObj.Data.Count == 0)
                    throw new Exception("传入参数为空");
                List<CommonArchiveDataDTOData> retlist = new List<CommonArchiveDataDTOData>();

                foreach (var dto in bpObj.Data)
                {
                    if (String.IsNullOrEmpty(dto.DocNo))
                        throw new Exception("必须传入单号[DocNo]");

                    TransferIn doc = TransferIn.Finder.Find($"DocNo='{dto.DocNo}'");
                    if (doc == null)
                    {
                        //新增逻辑
                        doc = CreateDoc(dto);
                        //修改单号
                        EntityUtils.UpdateDocNo<TransferIn>(doc.ID, dto.DocNo);
                        //审核
                        doc = ApproveDoc(doc);
                        //返回值
                        CommonArchiveDataDTOData ret = new CommonArchiveDataDTOData()
                        {
                            ID = doc.ID,
                            Code = doc.DocNo,
                        };
                        retlist.Add(ret);
                    }
                    else
                    {
                        //修改逻辑
                        throw new AITException(599, $"单号:{dto.DocNo}已经存在,不能生成!");
                    }
                }

                return ResultUtils.success(bpObj, bpObj.Data, retlist);
            }
            catch (Exception ex)
            {
                DeleteDoc(bpObj.Data);
                return ResultUtils.error(bpObj, bpObj.Data, ex);
            }
        }

        private void DeleteDoc(List<TransferInAITDTOData> data)
        {
            try
            {
                using (ISession session = Session.Open())
                {
                    foreach (var dto in data)
                    {
                        TransferIn doc = TransferIn.Finder.Find($"DocNo='{dto.DocNo}'");
                        if (doc != null)
                            doc.Remove();
                    }

                    session.Commit();
                }
            }
            catch(Exception ex) {
                LogUtils.Log("AIT删除失败\r\n"+ex.Message);
            }
        }

        private TransferIn ApproveDoc(TransferIn doc)
        {
            TransferInApproveSV approveSV = new TransferInApproveSV();
            approveSV.Data = new List<CopyOfCommonArchiveDataDTOData>
                            {
                                new CopyOfCommonArchiveDataDTOData
                                {
                                    Code=doc.DocNo,
                                }
                            };
            ResultDTOData resultDTOData = approveSV.Do();
            ResultUtils.CheckResult(resultDTOData);
            return doc;
        }

        private TransferIn CreateDoc(TransferInAITDTOData dto)
        {
            TransferIn doc = null;
            using(ISession session = Session.Open())
            {
                doc = TransferIn.Create();
                CreateHead(doc, dto);
                CreateLines(doc, dto);

                session.Commit();
            }
            return doc;
        }

        private void CreateLines(TransferIn doc, TransferInAITDTOData dto)
        {
            int rowno = 0;
            foreach (var linedto in dto.TransInLines)
            {
                rowno += 10;
                TransInLine line = TransInLine.Create(doc);
                if (linedto.DocLineNo > 0)
                {
                    line.DocLineNo = linedto.DocLineNo;
                }
                else
                {
                    line.DocLineNo = rowno;
                }
                line.Org = doc.Org;
                line.TransInOwnerOrg = doc.Org;
                line.TransInOrg = doc.Org;
                
                //来源单据处理
                if (linedto.SrcDocInfo == null) throw new Exception("SrcDocInfo 必填");
                String path = $"DocLineNo={linedto.SrcDocInfo.SrcDocLineNo} and TransferOut.DocNo='{linedto.SrcDocInfo.SrcDocNo}'";
                TransOutLine outline = TransOutLine.Finder.Find(path);
                if (outline == null) throw new Exception($"查询调出单行失败,path:[{path}]");
                TransOutSubLine outsubline = outline.TransOutSubLines[0];
                TransferOut outdoc = outline.TransferOut;
                line.SrcDocInfo = new UFIDA.U9.CBO.SCM.PropertyTypes.SrcDocInfo()
                {
                    SrcDocVer = outdoc.Version,
                    SrcDocTransType = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                    {
                        EntityType = outdoc.DocType.Key.EntityType,
                        EntityID = outdoc.DocType.Key.ID,

                    },
                    SrcDocSubLineNo = outsubline.DocLineNo,
                    SrcDocSubLine = new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                    {
                        EntityType = outsubline.Key.EntityType,
                        EntityID = outsubline.Key.ID,
                    },
                    SrcDocOrg = outdoc.Org,
                    SrcDocNo=outdoc.DocNo,
                    SrcDocLineNo=outline.DocLineNo,
                    SrcDocLine=new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                    {
                        EntityType = outline.Key.EntityType,
                        EntityID = outline.Key.ID,
                    },
                    SrcDocDate=outdoc.BusinessDate,
                    SrcDocBusiType=UFIDA.U9.Base.Doc.BusinessTypeEnum.GetFromValue(701),
                    SrcDoc=new UFIDA.U9.Base.PropertyTypes.BizEntityKey()
                    {
                        EntityType = outdoc.Key.EntityType,
                        EntityID = outdoc.Key.ID,
                    },
                };
                line.TransInWhMan=outsubline.TransInWhMan;
                line.TransInWh = outsubline.TransInWh;
                line.Project = outline.Project;//项目
                if (outline.LotInfo != null&& outline.LotInfo.LotMaster!=null)
                {
                    //批号
                    line.LotInfo = outline.LotInfo;
                }
                

                //料品/单位
                if (linedto.ItemInfo == null) throw new Exception("ItemInfo 必填");
                ItemMaster item = EntityUtils.GetEntityByCode<ItemMaster>(linedto.ItemInfo.ItemCode);
                if (outline.ItemInfo.ItemCode != item.Code)
                    throw new Exception($"来源料号[{outline.ItemInfo.ItemCode}]与传入料号[{item.Code}]不同");
                line.ItemInfo = new ItemInfo()
                {
                    ItemID=item,
                    ItemCode=item.Code,
                    ItemName=item.Name,
                };
                line.StoreUOM = item.InventoryUOM;
                line.StoreBaseUOM=item.InventoryUOM.BaseUOM;
                line.CostUOM=item.CostUOM;
                line.CostBaseUOM=item.CostUOM.BaseUOM;

                //数量/单价/金额
                line.StoreUOMQty=linedto.StoreUOMQty;
                line.CostUOMQty = linedto.StoreUOMQty;

                //其它字段
                line.SUTOSBURate = 1;
                line.SUToCURate = 1;
                line.CUTOCBURate = 1;
                line.StorageType = UFIDA.U9.CBO.Enums.StorageTypeEnum.GetFromValue(4);
                line.CostCurrency = EntityUtils.GetEntityByCode<Currency>("C001");

                //创建子行
                TransInSubLine subline= TransInSubLine.Create(line);
                subline.TransOutWhMan = outline.TransOutWhMan;
                subline.TransOutWh=outline.TransOutWh;
                subline.TransOutToTransInRate = 1;
                subline.TransOutOwnerOrg = doc.Org;
                subline.TransOutOrg=doc.Org;
                subline.TransInSUQty = line.StoreUOMQty;
                subline.TransInSU = line.StoreUOM;
                subline.SUTOSBURate = 1;
                subline.SUToCURate = 1;
                subline.StoreUOMQty = line.StoreUOMQty;
                subline.StoreUOM = line.StoreUOM;
                subline.StoreBaseUOM = line.StoreBaseUOM;
                subline.StorageType = line.StorageType;
                subline.SrcDocInfo=line.SrcDocInfo;
                subline.SOBAccountPeriod = doc.SOBAccountPeriod;
                subline.Org = line.Org;
                subline.ItemInfo = line.ItemInfo;
                subline.DocLineNo = 10;
                subline.CUTOCBURate = 1;
                subline.CostUOMQty = line.StoreUOMQty;
                subline.CostUOM= line.StoreUOM;
                subline.CostBaseUOM = line.CostBaseUOM;
                subline.CostCurrency = line.CostCurrency;
                subline.BalCurrency = subline.CostCurrency;

                //创建子行库位子表
                TransInBin bin1 = TransInBin.Create(subline);
                bin1.TimeForPickOrTally = doc.BusinessDate;
                bin1.StoreUOMQty=line.StoreUOMQty;
                bin1.BinLineNo = 10;

                //创建行库位子表
                TransInBin bin2= TransInBin.Create(line);
                bin2.TimeForPickOrTally = doc.BusinessDate;
                bin2.StoreUOMQty = line.StoreUOMQty;
                bin2.BinLineNo = 10;
            }
        }


        private void CreateHead(TransferIn doc, TransferInAITDTOData dto)
        {
            doc.DocNo = dto.DocNo;
            if(String.IsNullOrEmpty(dto.BusinessDate)) {
                throw new Exception("BusinessDate 必填");
            }
            doc.BusinessDate=DateTime.Parse(dto.BusinessDate);
            if (dto.TransInDocType == null) throw new Exception("TransInDocType 必填");
            doc.TransInDocType = EntityUtils.GetEntityByCode<TransInDocType>(dto.TransInDocType.Code);
            //调入类型 0-一步式 1-两步式
            doc.TransferInType = UFIDA.U9.CBO.SCM.Enums.TransferInType.GetFromValue(1);
            //来源类型 1-调出单
            doc.SrcDocType = UFIDA.U9.InvDoc.TransferIn.SrcDocTypeEnum.GetFromValue(1);
            doc.SOBAccountPeriod = EntityUtils.getPostPeriod(doc.BusinessDate);
            doc.Org = Context.LoginOrg;
            doc.IsVMIAAI = true;

            //创建期间子表
            TransInAccountPeriod per = TransInAccountPeriod.Create(doc);
            per.SOBAccountPeriod = doc.SOBAccountPeriod;
            per.SOB = EntityUtils.getSetofBooks();
        }
    }

	#endregion
	
	
}